package org.chen.aao.ai.controller;

import lombok.RequiredArgsConstructor;
import org.chen.aao.ai.service.IVoiceToTextService;
import org.chen.aao.common.ai.dto.VoiceHistoryResponse;
import org.chen.aao.common.ai.dto.VoiceToTextResponse;
import org.chen.aao.common.annotation.RateLimit;
import org.chen.aao.common.exception.BusinessException;
import org.chen.aao.common.response.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequiredArgsConstructor
public class VoiceToTextController {
    private final IVoiceToTextService voiceToTextService;

    @PostMapping("/voice-to-text")
    @RateLimit(key = "voice", count = 50, time = 3600)
    public Result<VoiceToTextResponse> voiceToText(@RequestParam("audio") MultipartFile audioFile,
                                                   @RequestParam(value = "language", required = false) String language,
                                                   HttpServletRequest httpRequest) {
        Long userId = getUserId(httpRequest);
        return Result.success(voiceToTextService.voiceToText(audioFile, language, userId));
    }

    @GetMapping("/voice-to-text-history")
    public Result<VoiceHistoryResponse> getVoiceToTextHistory(@RequestParam(value = "page", defaultValue = "1") int page,
                                                              @RequestParam(value = "size", defaultValue = "20") int size,
                                                              HttpServletRequest httpRequest) {
        Long userId = getUserId(httpRequest);
        return Result.success(voiceToTextService.getVoiceToTextHistory(userId, page, size));
    }

    private Long getUserId(HttpServletRequest request) {
        String userIdHeader = request.getHeader("X-User-Id");
        if (userIdHeader == null || userIdHeader.trim().isEmpty()) {
            throw new BusinessException("用户未登录");
        }
        try {
            return Long.valueOf(userIdHeader);
        } catch (NumberFormatException e) {
            throw new BusinessException("用户ID格式错误");
        }
    }
}
